package fun.lifepoem.blog.service;

import fun.lifepoem.blog.common.DateEnum;
import fun.lifepoem.blog.common.RedisKeys;
import fun.lifepoem.blog.domain.bo.TagBO;
import fun.lifepoem.blog.domain.vo.TagVO;
import fun.lifepoem.blog.mapper.TagMapper;
import fun.lifepoem.blog.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author Yiwyn
 * @create 2022/9/15 23:45
 */
@Service
@Slf4j
public class TagService {


    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private RedisService redisService;


    public List<TagVO> getTagList() {

        String date = DateUtils.getInstance().getDate(DateEnum.DATE_DAY);
        String key = RedisKeys.ALL_TAG + date;

        List<TagVO> tags = (List<TagVO>) redisService.getKey(key);
        if (!CollectionUtils.isEmpty(tags)) {
            return tags;
        } else {
            List<TagBO> tagList = tagMapper.selectAllTag();
            List<TagVO> tagVOList = tagList.stream().map(TagVO::getTagVO).collect(Collectors.toList());
            //调整taglist为树形结构
            List<TagVO> oneLeve = tagVOList.stream().filter(p -> p.getParentId().equals("0")).collect(Collectors.toList());

            for (TagVO tagVO : oneLeve) {
                setChild(tagVOList, tagVO);
            }


            redisService.setKey(key, oneLeve, 24, TimeUnit.HOURS);
            return oneLeve;
        }
    }


    //递归生成树形结构
    private void setChild(List<TagVO> tagVOList, TagVO tagVO) {

        if (CollectionUtils.isEmpty(tagVOList) || tagVO == null) {
            return;
        }

        List<TagVO> temp = tagVOList.stream()
                .filter(p -> p.getParentId().equals(tagVO.getId())).collect(Collectors.toList());
        tagVO.setChildTags(temp);
        for (TagVO vo : temp) {
            setChild(tagVOList, vo);
        }
    }

}
